home *** CD-ROM | disk | FTP | other *** search
/ Macwelt 1 / Macwelt DVD 1.toast / Web-Publishing / HTML-Editoren / Alpha ƒ / Mode Examples / Python-Example.py < prev    next >
Encoding:
Python Source  |  2000-10-30  |  2.0 KB  |  77 lines

  1. # Python-Example.py
  2. # Distributed as an example of Alpha's Python mode.
  3. #
  4. # Pyth mode is available at
  5. # <http://www.python.org/emacs/python-mode/>
  6. #
  7.  
  8. # Source of original document:
  9. # <http://www.enme.ucalgary.ca/~nascheme/python/>
  10. # Reproduced with the permission of the author.
  11. #
  12.  
  13. #!/usr/bin/env python
  14. #
  15. # Create HTML from a GIF file and text input.
  16. #
  17. # Usage: gif2html.py pic.gif < input > output.html
  18. #
  19. # Neil Schemenauer <nascheme@enme.ucalgary.ca>
  20.  
  21. import Image
  22. import sys
  23. import string
  24. import htmlentitydefs
  25.  
  26. # reverse table for HTML entity names
  27. entitydefs = {}
  28. for name, value in htmlentitydefs.entitydefs.items():
  29.     entitydefs[value] = name
  30.  
  31. def getc(file):
  32.     while 1:
  33.         c = file.read(1)
  34.         if not c:
  35.             raise EOFError
  36.         if c not in string.whitespace:
  37.             return c
  38.  
  39. def main(graphic, input, output, transparent=(255, 0, 255)):
  40.     output.write('<html><body bgcolor=#000000><basefont size=1><pre>')
  41.     im = Image.open(graphic)
  42.     im = im.convert('RGB')
  43.     # try to keep aspect the same (make height 2/3 of original)
  44.     im = im.resize((im.size[0], im.size[1]*3/5))
  45.     d = im.getdata()
  46.     l, w = im.size
  47.     last_pixel = None
  48.     font_open = 0
  49.     for i in range(w):
  50.         for j in range(l):
  51.             pixel = d[i*l+j]
  52.             if pixel == transparent:
  53.                 output.write(' ')
  54.             else:
  55.                 c = getc(input)
  56.                 if pixel != last_pixel:
  57.                     if font_open:
  58.                         output.write('</font>')
  59.                     font_open = 1
  60.                     output.write('<font color=#%.2x%.2x%.2x>' % pixel)
  61.                 if entitydefs.has_key(c):
  62.                     c = '&%s;' % entitydefs[c]
  63.                 output.write(c)
  64.                 last_pixel = pixel
  65.         output.write('\n')
  66.  
  67.     output.write("""</font></pre><br>
  68.         <a href="http://www.enme.ucalgary.ca/~nascheme/python/gif2html.py">
  69.         gif2html.py</a></body></html>""")
  70.  
  71. if __name__ == '__main__':
  72.     main(sys.argv[1], sys.stdin, sys.stdout)
  73.